class HookCodeFactory {
  args({ after, before } = {}) {
    let allArgs = this.options.args
    if (before) allArgs = [before].concat(allArgs)
    if (after) allArgs = allArgs.concat(after)
    return allArgs.join(',')  // ["name", "age"] => name, age
  }
  header() {
    return `"use strict";var _context;var _x = this._x;`
  }
  content(type) {
    let code = ''
    switch (type) {
      case 'sync':
        for (let i = 0; i < this.options.taps.length; i++) {
          code += `var _fn${i} = _x[${i}];_fn${i}(${this.args()});`
        }
        break
      case 'async':
        code = `var _counter = ${this.options.taps.length};var _done = (function () {
          _callback();
        });`
        for (let i = 0; i < this.options.taps.length; i++) {
          code += `var _fn${i} = _x[${i}];_fn${i}(${this.args()}, (function () {
            if (--_counter === 0) _done();
          }));`
        }
        break
    }
    return code
  }
  setup(instance, options) {  // 先准备后续需要使用到的数据
    this.options = options  // 这里的操作在源码中是通过 init 方法实现，而我们当前是直接挂在了 this 身上
    instance._x = options.taps.map(o => o.fn)   // this._x = [f1, f2, ....]
  }
  create() { // 核心就是创建一段可执行的代码体然后返回
    // fn = new Function("name, age", "var _x = this._x, var _fn0 = _x[0]; _fn0(name, age);")
    const type = this.options.type
    const argsParams = type === 'sync' ? '' : { after: '_callback' }
    return new Function(
      this.args(argsParams),
      this.header() + this.content(this.options.type)
    )
  }
}

module.exports = HookCodeFactory
